package com.fjw.controller;

import com.fjw.captcha.Captcha1;
import com.fjw.pojo.User;
import com.fjw.service.UserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author fjw
 * @version 1.0
 * @date 2019/11/1 15:33
 */


/**
 * 用户的controller
 */
@Controller
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String register(User user,String roleName){
        Integer roleId;

        if (roleName.equals("老师")){
            roleId=1;
        }else {
            roleId=2;
        }
        userService.register(user,roleId);
        return "login";
    }

    //生成验证码的handler
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Captcha1.generateCaptcha(request,response);
    }
    //验证验证码是否正确
    @PostMapping("/checkCode")
    public void checkCode(HttpSession session, String vcode, HttpServletResponse response) throws IOException {
        //从session中再获取一个验证码
        Integer captcha1 = (Integer) session.getAttribute("captcha");
        String captcha = String.valueOf(captcha1);
        log.info("session中的验证码"+captcha);
        //进行比对 返回0 或者1
        if (vcode.equalsIgnoreCase(captcha)){
            //验证成功
            response.getWriter().write("0");
        }else {
            //验证失败
            response.getWriter().write("1");
        }
    }

    //登录功能
    @PostMapping("/login")
    public String login(User user){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        SecurityUtils.getSubject().login(usernamePasswordToken);
        return "redirect:/listClaz";
    }
    //显示班级内学生信息
    @GetMapping("/listStudent")
    public String listStudent(Integer clazId, Model model,Integer _pageNum){
        //接受参数
        Integer pageNum=1;
        if (_pageNum!=null){
            pageNum = _pageNum;
        }
        PageInfo<User> pageInfo = userService.listByClazId(clazId,pageNum);
        model.addAttribute("pageInfo", pageInfo);
        //跳转到 显示学生信息的界面
        return "listStudent";
    }
}
